﻿using UnityEngine;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
/// <summary>
/// 管理向服务器发送的消息
/// </summary>
public class RequestMessageManager 
{
    //发送消息队列
    private ConcurrentQueue<MessageRequest> sendList = new ConcurrentQueue<MessageRequest>();
    private long lastSendTime = DateUtil.CurrentMillTime();
    private MessageRequest currentRequest = null;
    private readonly XinyueSocketClient socketClient;
    private int seqId = 0;

    public RequestMessageManager(XinyueSocketClient socketClient)
    {
        this.socketClient = socketClient;
    }

    public MessageRequest GetCurrentMessageRequest()
    {
        return currentRequest;
    }
    public void DeleteCurrentMessageRequest()
    {
        this.sendList.TryDequeue(out _);
    }
    public void Update()
    {
        this.FixSendRequest();
    }
    private void FixSendRequest()
    {
        MessageRequest request = null;
        bool flag = this.sendList.TryPeek(out request);
        if (flag && request != null)
        {
            MessageHeader header = request.Header;
            int nowSeqId = currentRequest == null ? 0 : currentRequest.Header.SeqId;

            if (nowSeqId == 0 || header.SeqId - nowSeqId == 1)
            {
                //这时才向服务器发送消息
                currentRequest = request;
                byte[] bytes = CodecFactory.EncodeMessage(request);
                socketClient.SendToServer(bytes);

            }
            else if (header.SeqId == nowSeqId)
            {
                //判断是否超时，如果超时，再发送请求
            }
        }
    }

    public void SendRequest(MessageIDEnum messageID, object message, OnResponseMessageHandler responseHandler)
    {
        MessageRequest request = new MessageRequest();
        MessageHeader header = new MessageHeader();
        header.MessageType = 1;
        header.MessageId = (int)messageID;
        lock (this)
        {

            int _seqId = ++this.seqId;
            header.SeqId = _seqId;
        }
        header.ClientSendTime = DateUtil.CurrentMillTime();
        request.Header = header;
        Dictionary<string, object> data = new Dictionary<string, object>
        {
            { "msg", message }
        };
        request.Body = data;
        request.ResponseHandler = responseHandler;

        this.sendList.Enqueue(request);

    }

}
